﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit.Design;
using AjaxControlToolkit;
using System.Data;
using System.Data.SqlClient;
using BCDataCenter;
using BCDataCenter.BOL;
using CSharp_MessageBox;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

public partial class WebUserControl_NhapDoigiaban : System.Web.UI.UserControl
{
    BCDataCenter.DataAccessLayer.DAL dtt;
    private static string trntyp = "";
    private static DataTable dt = new DataTable();
    private static DataSet dataset = new DataSet();
    private static bool flag = false,edited =false,update = false ;
    private static int index = 0;
    private static string sitecode = "";
    private static string location = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            flag = false;
            ImageButton2.Enabled = false;
            getIntxtype();
            tb_tenhang.Enabled = false;
            tb_giacu.Enabled = false;
           // bindGridView();           
            trntyp = Ddl_Loainghiepvu.SelectedValue.ToString();
            tb_giamoi.Enabled = false;
            Page.SetFocus(tb_mahang);
            tb_mahang.Enabled = false;
            ImageButton2.Enabled = false;
            //-------------------
            sitecode = Session["Sitecode"].ToString();
            string error = "";
            DataSet Ds = new DataSet();
            dtt = new BCDataCenter.DataAccessLayer.DAL();
            Ds = dtt.MyExecuteReader(ref error, "select location from INLOCD where sitecode ='" + sitecode + "'", CommandType.Text);
            if (Ds.Tables[0].Rows.Count >= 1)
            {
                location = Ds.Tables[0].Rows[0][0].ToString();
            }
            else
                return;
            Ds.Dispose();
        }
        
        
    }
    
    private void getIntxtype()
    {
        string error = "";
        dtt = new BCDataCenter.DataAccessLayer.DAL();
        DataSet DS;
        DS = dtt.MyExecuteReader(ref error, "get_Intxtyp", CommandType.StoredProcedure);
        //DS = dt.MyExecuteReader(ref error, "get_inlocd", CommandType.StoredProcedure);
        Ddl_Loainghiepvu.DataSource = DS.Tables[0];
        Ddl_Loainghiepvu.DataTextField = "description";
        Ddl_Loainghiepvu.DataValueField = "trntyp";
        Ddl_Loainghiepvu.DataBind();
        DS.Dispose();
    }

    protected void bindGridView()
    {
        DataTable dtab = dTable();
        DataRow d = dt.NewRow(); 
        d["itemkey"] = null;
        d["description"] = null;
        d["oldprice"] = null;
        d["newprice"] = null;        
        dt.Rows.Add(d);
        gv_chitiet.DataSource = dt;
        gv_chitiet.DataBind();
    }
    public DataTable dTable()
    {
        dt = new DataTable();
        dt.Columns.Add("itemkey");
        dt.Columns.Add("description");
        dt.Columns.Add("oldprice");
        dt.Columns.Add("newprice");
        dt.Columns.Add(" ");       
        return dt;
    }
    protected void tb_mahang_TextChanged(object sender, EventArgs e)
    {
        string itemkey = tb_mahang.Text.ToString();
        string error = "";
        if (!tb_mahang.Text.Equals(String.Empty))
        {
            string str = tb_mahang.Text;
            int index = str.IndexOf("|");
            if (index == -1)
            {
                DataTable dtMH = new BWNhapHoaDonBanHang().dsInfoMatHang(ref error, str).Tables[0];
                if (dtMH.Rows.Count != 0)
                {
                    tb_mahang.Text = dtMH.Rows[0]["MaHang"].ToString();
                    tb_tenhang.Text = dtMH.Rows[0]["TenHang"].ToString();

                    tb_giamoi.Enabled = true;
                    Page.SetFocus(tb_giamoi);
                }
                else
                {
                    uscMsgBox1.AddMessage("Không có mặt hàng này.", uscMsgBox.enmMessageType.Error);
                    tb_mahang.Focus();
                    return;
                }
            }
            else
            {
                tb_mahang.Text = str.Substring(0, index - 1);
                tb_tenhang.Text = str.Substring(index + 2, str.Length - index - 2);
                tb_giamoi.Enabled = true;
                Page.SetFocus(tb_giamoi);
            }

        }
        //dtt = new BCDataCenter.DataAccessLayer.DAL();
        //bool isexit = false;
        //isexit = dtt.IsExistFromSQL("checkExit", CommandType.StoredProcedure, ref error, new SqlParameter("@itemkey", itemkey));
        //if (isexit)
        //{
        //    GetItem();
        //    tb_tenhang.Text = dataset.Tables[0].Rows[0][2].ToString();
        //    tb_giacu.Text = dataset.Tables[0].Rows[0][3].ToString();           
        //    TabContainer1.ActiveTabIndex = 0;
        //    tb_giamoi.Enabled = true;
        //    Page.SetFocus(tb_giamoi);
        //}
        //else
        //{
        //    GetItems();
        //    gv_timkiem.DataSource = dataset.Tables[0];
        //    gv_timkiem.DataBind();
        //    tb_giamoi.Enabled = false;
        //    TabContainer1.ActiveTabIndex = 1;
        //    Page.SetFocus(tb_giamoi);
        //}


    }
    protected void Ddl_sochungtu_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        string tem = Ddl_sochungtu.SelectedItem.Text.ToString();
        if (tem == "Chon hoa don......")
        { }
        else
        {
            tem = tem.Substring(2, 8);
            tem = tem.Substring(0, 2) + "/" + tem.Substring(2, 2) + "/" + tem.Substring(4, 4);
            txt_ngay.Text = tem;
            reloadIntxd();
        }
    }
   protected  void bt_chon_Click(object sender, EventArgs e)
    {
        reloadIntxd();
    }

   private void reloadIntxd()
   {
       if (flag == false)
       {
           update = true;
           dtt = new BCDataCenter.DataAccessLayer.DAL();
           trntyp = Ddl_Loainghiepvu.SelectedValue.ToString();
           DataSet ds = new DataSet();
           string docdate = txt_ngay.Text.ToString();
           string docno = Ddl_sochungtu.SelectedItem.ToString();
           string error = "";
           ds = dtt.MyExecuteQuery(ref error, "get_intxdetail", CommandType.StoredProcedure, new SqlParameter("@docdate", docdate), new SqlParameter("@docno", docno), new SqlParameter("@trntyp", trntyp));
           gv_chitiet.DataSource = ds.Tables[0];
           gv_chitiet.DataBind();
           tb_mahang.Enabled = true;
           ImageButton2.Enabled = true;
           Session["dt"] = ds.Tables[0];
       }
   }
    protected void tb_giamoi_TextChanged(object sender, EventArgs e)
    {
        if (edited == false)
        {
            try
            {
                DataTable dts = dTable();
                if (Session["dt"] != null)
                    dts = (DataTable)Session["dt"];
                DataRow dr = dts.NewRow();
                dr["itemkey"] = tb_mahang.Text.ToString();
                dr["description"] = tb_tenhang.Text.ToString();
                dr["oldprice"] = 0;
                dr["newprice"] = tb_giamoi.Text.ToString();
                dts.Rows.Add(dr);
                gv_chitiet.DataSource = dts;
                gv_chitiet.DataBind();
                Session["dt"] = dts;
                tb_mahang.Text = "";
                tb_tenhang.Text = "";
                tb_giacu.Text = "";
                tb_giamoi.Text = "";
                tb_giamoi.Enabled = false;
                Page.SetFocus(tb_mahang);
            }
            catch { return; }
        }
        else
        {
            try
            {
                dt = (DataTable)Session["dt"];
                dt.Rows[index]["newprice"] = tb_giamoi.Text.ToString();
                gv_chitiet.DataSource = dt;
                gv_chitiet.DataBind();
                Session["dt"] = dt;
                tb_mahang.Text = "";
                tb_tenhang.Text = "";
                tb_giacu.Text = "";
                tb_giamoi.Text = "";
                tb_giamoi.Enabled = false;
                tb_mahang.Enabled = true;
                Page.SetFocus(tb_mahang);
            }
            catch { return; }
        }
        edited = false;
    }
    public void GetItem()
    {
        string itemkey = tb_mahang.Text.ToString();
        dtt = new BCDataCenter.DataAccessLayer.DAL();
        string error="";
        dataset = dtt.MyExecuteQuery(ref error, "Get_Item", CommandType.StoredProcedure, new SqlParameter("@itemkey", itemkey));
        
    }
    public void GetItems()
    {
        string itemkey = tb_mahang.Text.ToString();
        dtt = new BCDataCenter.DataAccessLayer.DAL();
        string error = "";
        dataset = dtt.MyExecuteQuery(ref error, "Get_Items", CommandType.StoredProcedure, new SqlParameter("@itemkey", itemkey));

    }
   
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {

    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        string docno = "";
        string error = "";
        string docdate = txt_ngay.Text.ToString();
        dtt = new BCDataCenter.DataAccessLayer.DAL();
        trntyp = Ddl_Loainghiepvu.SelectedValue.ToString();
        if (flag == false)
        {
            if (update == true)
            {
                
                docno = Ddl_sochungtu.SelectedItem.Text.ToString();
                
                bool i = dtt.MyExecuteNonQuery("edit_indxt", CommandType.StoredProcedure, ref error, new SqlParameter("@docno", docno));
                if (i)
                {
                    docno = docno.Substring(11, docno.Length - 11);
                    error = LuuChungtu(error, docdate, docno);
                }
            }
            else
            {
                uscMsgBox1.AddMessage("Phải ấn nút tạo mới trước", uscMsgBox.enmMessageType.Error) ;
            }
        }
        else
        {
           
            if (docdate == "")
            {
                uscMsgBox1.AddMessage("ban phai chon ngay", uscMsgBox.enmMessageType.Error);
            }
            else
            {
                if (trntyp == "0")
                { uscMsgBox1.AddMessage("Bạn phải chọn loại chứng từ", uscMsgBox.enmMessageType.Error); }
                else
                {
                    //lb_loi.Text = "";
                    DataSet ds = new DataSet();
                    ds = dtt.MyExecuteQuery(ref error, "get_docnonext", CommandType.StoredProcedure, new SqlParameter("@trntyp", trntyp));
                    docno = ds.Tables[0].Rows[0][0].ToString();
                    float tem = float.Parse(docno) + 1;
                    docno = tem.ToString();
                    error = LuuChungtu(error, docdate, docno);                           
                  
                }
            }
        }
    }

    private string LuuChungtu(string error, string docdate,string docno)
    {
        dtt = new BCDataCenter.DataAccessLayer.DAL();
        trntyp = Ddl_Loainghiepvu.SelectedValue.ToString();
        //if(gv_chitiet.Rows.Count==1)
            
        docno = trntyp + "_" + docdate.Substring(0, 2) + docdate.Substring(3, 2) + docdate.Substring(6, 4) + "_" + docno;

        int row = gv_chitiet.Rows.Count;
        if (row == 1)
        {
            if (gv_chitiet.Rows[0].Cells[0].Text.ToString() == "&nbsp;")
            {
                uscMsgBox1.AddMessage("Không có mặt hàng nào", uscMsgBox.enmMessageType.Error);
            }
            else
            {
                for (int i = 0; i < row; i++)
                {

                    string itemkey = gv_chitiet.Rows[i].Cells[0].Text.ToString();
                    string newprice = gv_chitiet.Rows[i].Cells[3].Text.ToString();
                    string oldprice = gv_chitiet.Rows[i].Cells[2].Text.ToString();
                    float stockqty = 0;
                    if (trntyp != "F")
                    {
                        stockqty = float.Parse(newprice);
                    }
                    float stocprice = float.Parse(newprice);
                    float stockcost = 0;
                    dtt.MyExecuteNonQuery("insert_intxd", CommandType.StoredProcedure, ref error, new SqlParameter("@itemkey", itemkey), new SqlParameter("@stocprice", stocprice), new SqlParameter("@trntyp", trntyp), new SqlParameter("@stockcost", stockcost), new SqlParameter("@docno", docno), new SqlParameter("@docdate", docdate), new SqlParameter("@stockqty", stockqty),new SqlParameter ("@location",location),new SqlParameter("@sitecode",sitecode));
                   
                    bindGridView();
                    Session["dt"] = dTable();
                }
                uscMsgBox1.AddMessage("Hoàn thành lưu thông tin ", uscMsgBox.enmMessageType.Success);
                dtt.MyExecuteNonQuery("update_Intxdnum", CommandType.StoredProcedure, ref error, new SqlParameter("@trntyp", trntyp));
            }
        }
        else
        {
            for (int i = 0; i < row; i++)
            {

                string itemkey = gv_chitiet.Rows[i].Cells[0].Text.ToString();
                string newprice = gv_chitiet.Rows[i].Cells[3].Text.ToString();
                string oldprice = gv_chitiet.Rows[i].Cells[2].Text.ToString();
                float stockqty = 0;
                if (trntyp != "F")
                {
                    stockqty = float.Parse(newprice);
                    oldprice = "0";
                }

                float stocprice = float.Parse(newprice);
                float stockcost = float.Parse(oldprice);
                dtt.MyExecuteNonQuery("insert_intxd", CommandType.StoredProcedure, ref error, new SqlParameter("@itemkey", itemkey), new SqlParameter("@stocprice", stocprice), new SqlParameter("@trntyp", trntyp), new SqlParameter("@stockcost", stockcost), new SqlParameter("@docno", docno), new SqlParameter("@docdate", docdate), new SqlParameter("@stockqty", stockqty), new SqlParameter("@location", location), new SqlParameter("@sitecode", sitecode));
               
            }
            uscMsgBox1.AddMessage("Hoàn thành lưu thông tin ", uscMsgBox.enmMessageType.Success);
            dtt.MyExecuteNonQuery("update_Intxdnum", CommandType.StoredProcedure, ref error, new SqlParameter("@trntyp", trntyp));           
        }
        Ddl_sochungtu.Items.Clear();
        Ddl_sochungtu.Items.Add(docno);
        return error;
    }
   
    
    protected void gv_chitiet_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void gv_chitiet_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    }
    protected void gv_chitiet_RowEditing(object sender, GridViewEditEventArgs e)
    {
        index = e.NewEditIndex;
        tb_mahang.Text = gv_chitiet.Rows[index].Cells[0].Text.ToString();
        tb_tenhang.Text = gv_chitiet.Rows[index].Cells[1].Text.ToString();
        tb_giacu.Text = gv_chitiet.Rows[index].Cells[2].Text.ToString();
        tb_giamoi.Enabled = true;
        Page.SetFocus(tb_giamoi);
        edited = true;
    }
    protected void gv_chitiet_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        
        dt = (DataTable)Session["dt"];        
        int i = e.RowIndex;
       // DataRow rowDel = dt.Rows[i];
        dt.Rows.RemoveAt(i);
        //dt.Rows.Remove(rowDel);
        gv_chitiet.DataSource = dt;
        gv_chitiet.DataBind();
        Session["dt"]=dt;
       
    }
    protected void gv_chitiet_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

    }
    
   
    protected void bt_selectitem_Click(object sender, EventArgs e)
    {
        
    }
    protected void gv_timkiem_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("selectItem"))
        {
            GridViewRow gvr = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            try
            {

                tb_mahang.Text = dataset.Tables[0].Rows[gvr.RowIndex]["itemkey"].ToString();
                tb_tenhang.Text = dataset.Tables[0].Rows[gvr.RowIndex]["description"].ToString();
                tb_giacu.Text = dataset.Tables[0].Rows[gvr.RowIndex]["price"].ToString();
                tb_giamoi.Enabled = true;
                Page.SetFocus(tb_giamoi);
               
            }
            catch
            {
                return;
            }
        }
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        string error = "";
        try
        {
            
            DataSet Ds = new DataSet();
            dtt = new BCDataCenter.DataAccessLayer.DAL();
            Ds = dtt.MyExecuteReader(ref error, "SELECT     [Closed Date] FROM mis where sitecode ='" + sitecode + "'", CommandType.Text);
            if (Ds.Tables[0].Rows.Count >= 1)
            {
                string tmp = Ds.Tables[0].Rows[0][0].ToString();
                DateTime dateTest = DateTime.Parse(tmp, new CultureInfo("fr-FR", false));
                dateTest = dateTest.AddDays(double.Parse("1"));
                txt_ngay.Text = dateTest.ToString("dd/MM/yyyy");
                flag = true;
                ImageButton2.Enabled = true;
                tb_mahang.Enabled = true;
                getIntxtype();
                Ddl_sochungtu.Items.Clear();
                Ddl_sochungtu.Enabled = false;
                bindGridView();
                Session["dt"] = null;
                update = false;
                Ds.Dispose();
                edited = false;
            }
        }
        catch (Exception ex)
        { 
            uscMsgBox1.AddMessage(error + "\n" +ex.Message, uscMsgBox.enmMessageType.Error);
            return;
        }
    }

    protected void Ddl_Loainghiepvu_SelectedIndexChanged(object sender, EventArgs e)
    {
        trntyp = Ddl_Loainghiepvu.SelectedValue.ToString();
        if (trntyp == "0")
        { }
        else
        {
            if (trntyp == "F")
            {
                gv_chitiet.Columns[3].HeaderText = "Giá Mới";
                Label8.Text = "Giá mới";
                gv_chitiet.Columns[2].HeaderText = "Giá cũ";
                Label7.Text = "Giá cũ";
            }
            else
            {
                {
                    gv_chitiet.Columns[3].HeaderText = "Số lượng";
                    Label8.Text = "Số lượng";
                    gv_chitiet.Columns[2].HeaderText = "Giá";
                    Label7.Text = "Giá";
                }
            }
            if (flag == false)
            {
                Ddl_sochungtu.Enabled = true;
                Ddl_sochungtu.Items.Clear();
                gettranno(trntyp);
            }
        }
        Session["dt"] = null;
        bindGridView();
        //lb_loi.Text = "";
    }
    
     protected void gettranno( string loainghievu)
    {
        string error = "";
        try
        {
            dtt = new BCDataCenter.DataAccessLayer.DAL();
            DataSet DS = new DataSet();
            DS = dtt.MyExecuteQuery(ref error, "get_intxdtrano", CommandType.StoredProcedure, new SqlParameter("@trntyp", loainghievu), new SqlParameter("@sitecode", sitecode));
            if (DS.Tables[0].Rows.Count >= 1)
            {
                Ddl_sochungtu.DataSource = DS.Tables[0];
                Ddl_sochungtu.DataTextField = "docno";
                Ddl_sochungtu.DataValueField = "docno";
                Ddl_sochungtu.DataBind();
                //DS.Dispose();
            }
        }
        catch { return; }
    }

     protected void imb_tim_Click(object sender, ImageClickEventArgs e)
     {
         Ddl_sochungtu.Enabled = true;
         flag = false;
         bindGridView();

     }
   
     protected void imb_xoa_Click(object sender, ImageClickEventArgs e)
     {
         string error = "";
         dtt = new BCDataCenter.DataAccessLayer.DAL();
         string tmp = Ddl_sochungtu.SelectedItem.Text.ToString();
         if (tmp == "")
            uscMsgBox1.AddMessage("khong co so chung tu nao", uscMsgBox.enmMessageType.Error);
         else 
         {
             if (tmp == "Chon hoa don......")
                 uscMsgBox1.AddMessage("ban phai chon so chung tu", uscMsgBox.enmMessageType.Error);
             else 
             {
                bool i = dtt.MyExecuteNonQuery("delete_indxt", CommandType.StoredProcedure, ref error, new SqlParameter("@docno", tmp));
                if (i)
                {
                    uscMsgBox1.AddMessage("So chung tu "+tmp +" da xoa", uscMsgBox.enmMessageType.Success);
                    gettranno(trntyp);
                    bindGridView();
                }
             }
         }
     }
}
